<template>
  <div :class="{'mobile-table mobile-pt mobile-min-height':showMobilePage, 'min-fill-page image-list': !showMobilePage}">
    <div v-if="!showMobilePage" style="position:relative;margin-bottom:16px;">
      <FilterInput
        ref="FilterToolRef"
        v-model="paramsObj"
        :filter-list="filterList"
        show-search-btn
        @handelClick="queryClick"
        @queryEmpty="queryEmpty"
        @filterTagStatus="filterTagStatus"
      />
    </div>
    <div class="table-list">
      <div v-loading="listLoading" style="min-height: 300px">
        <el-row v-if="list.items.length" ref="scrollRef" :style="{maxHeight: setTableHeight + 'px'}" :gutter="8" type="flex" class="img-wrap">
          <el-col v-for="(item, index) in list.items" :span="4" :key="`${item.id}${index}`">
            <div class="item">
              <el-image
                :src="item.url"
                fit="cover"
                class="img"
                style="width: 100%; height: 300px;"
              />
              <div class="hover-item">
                <div class="flex-center mb12">
                  <el-tooltip :content="`订单编号：${ item.orderSn || '--' }`" class="flex-1" placement="top">
                    <div class="ellipsisOne">订单编号：{{ item.orderSn || '--' }}</div>
                  </el-tooltip>
                  <div v-if="item.orderId" class="flex-center check" @click="toOrder(item)">查看<i class="el-icon-arrow-right"/></div>
                </div>
                <div class="flex-center mb12">
                  <el-tooltip :content="`发布链接：${ item.publishUrl || '--' }`" class="flex-1" placement="top">
                    <div class="flex-1 ellipsisOne">发布链接：{{ item.publishUrl || '--' }}</div>
                  </el-tooltip>
                  <a :href="item.publishUrl" target="_blank" class="check">查看<i class="el-icon-arrow-right"/></a>
                </div>
                <div class="mb12">
                  <el-tooltip :content="`账号：${ item.account || '--' }`" class="flex-1" placement="top">
                    <div class="flex-1 ellipsisOne">账号：{{ item.account || '--' }}</div>
                  </el-tooltip>
                </div>
                <el-tooltip :content="`平台：${ item.platformTypeName || '--' }`" class="flex-1" placement="top">
                  <div class="flex-1 ellipsisOne">平台：{{ item.platformTypeName || '--' }}</div>
                </el-tooltip>
                <div class="footer">
                  <div>{{ format(item.createTime,'YYYY/MM/DD') }}</div>
                  <div v-if="hasRouteAuth('publish:screenshot:manage')" class="btn-wrap">
                    <div v-if="canPick(item)" class="img-btn">
                      <el-tooltip v-if="!pickLoadingIds.includes(item.id)" content="替换采集" class="flex-1" placement="top">
                        <img :src="pickIcon" class="img" @click="imageRePick(item)">
                      </el-tooltip>
                      <i v-else class="el-icon-loading"/>
                    </div>
                    <div class="img-btn">
                      <el-tooltip content="放大" class="flex-1" placement="top">
                        <img :src="bigIcon" class="img" @click="preview(item)">
                      </el-tooltip>
                    </div>
                    <div class="img-btn">
                      <el-tooltip content="下载" class="flex-1" placement="top">
                        <img :src="downloadIcon" class="img" @click="download(item)">
                      </el-tooltip>
                    </div>
                  </div>
                </div>
              </div>
              <div v-if="isSelecting && canPick(item)" class="select-box">
                <div class="select-mask" />
                <el-checkbox :value="selectedIds ? selectedIds.includes(item.singleId) : false" @change="e => handleSelect(e, item)" />
              </div>
            </div>
          </el-col>
        </el-row>
        <EmptyPlaceholder v-else style="margin-bottom: 24px" class="no-bg"/>
      </div>
      <el-row v-if="showMobilePage" type="flex" justify="left">
        <el-pagination
          v-show="list.total > 0"
          :current-page.sync="page"
          :page-size="perPage"
          :total="list.total"
          :small="true"
          :page-sizes="[20, 50, 100, 250, 500]"
          :layout="pageLayout"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-row>
      <fixed-pagination style="justify-content: space-between;">
        <template v-if="showMobilePage">
          <FilterInput
            ref="FilterToolRef"
            v-model="paramsObj"
            :filter-list="filterList"
            show-search-btn
            is-show-config
            show-mobile-icon
            @handelClick="queryClick"
            @queryEmpty="queryEmpty"
            @filterTagStatus="filterTagStatus"
          />
        </template>
        <el-button v-if="!isSelecting" type="primary" size="small" @click="isSelecting = true">批量管理</el-button>
        <div v-else class="flex-center">
          <el-button size="small" type="primary" @click="selectAll">全选</el-button>
          <el-button size="small" type="info" class="cancel-btn-style" @click="handleCancel">取消</el-button>
          <PlainCreateBtn :loading="batchLoading" :show-icon="false" :disabled="!selectedIds.length" type="primary" size="small" style="height: 32px;margin-left: 16px;;" @click="batchPick">替换采集</PlainCreateBtn>
          <SelectionNum :select-item="selectData" @clearMixinSelection="clearMixinSelection" />
        </div>
        <el-pagination
          v-if="!showMobilePage"
          v-show="list.total > 0"
          :current-page.sync="page"
          :page-size="perPage"
          :total="list.total"
          :page-sizes="[20, 50, 100, 250, 500]"
          layout="total, prev, pager, next, sizes, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </fixed-pagination>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import { getImageList, imageRePick, batchReplacePick } from '@/api/publish';
import { platformList } from '@/api/select';
import { format } from '@/filters/date';
import { paramsRangeFormat, paramsAryToStr } from '@/utils/paramsFormat';
import { hasRouteAuth } from '@/utils/permission';
import { downloadFile } from '@/utils';
import mobileTable from '@/mixins/mobileTable';
import TableAdaptive from '@/mixins/tableAdaptive';
import bigIcon from '@/assets/target/big.png';
import pickIcon from '@/assets/target/pick.png';
import downloadIcon from '@/assets/target/download.png';

export default {
  components: {
    EmptyPlaceholder
  },
  mixins: [TableAdaptive, mobileTable],
  data() {
    return {
      bigIcon,
      pickIcon,
      downloadIcon,
      list: {
        items: [],
        total: 0,
        isInit: true
      },
      page: 1,
      perPage: 100,
      sortType: '',
      sortName: '',
      isSelecting: false, // 选择状态
      selectedData: [
        { page: 1, data: [] } // 单独存储每页勾选数据方便全选和取消全选操作
      ],
      pickLoadingIds: [],
      paramsObj: {},
      batchLoading: false,
      listLoading: false,
      rangeKeyArr: [{ attr: 'createTime', start: 'createStartTime', end: 'createEndTime', type: 'time', addTime: true }],
      arrayKeyArr: ['platformId'],
      orderPlatformOption: []
    };
  },
  computed: {
    ...mapState({
      userInfo: state => state.user.userInfo,
      'showMobilePage': state => state.app.showMobilePage
    }),
    selectedIndex() { // 当前页选中数据在selectedData中的索引
      return this.selectedData.findIndex(it => it.page === this.page);
    },
    selectedIds() { // 当前页选中的数据ids
      return this.selectedData[this.selectedIndex] ? this.selectedData[this.selectedIndex].data.map(it => it.singleId).join(',') : '';
    },
    selectData() { // 所有选中的数据
      let res = [];
      if (this.selectedData.length) {
        this.selectedData.forEach(item => {
          res = res.concat(item.data);
        });
      }
      return res;
    },
    filterList() {
      const arr = [
        { keyword: 'account', name: '账号', type: 'input', labelWidth: '70px' },
        { keyword: 'publishUrl', name: '发布链接', type: 'input', labelWidth: '70px' },
        { keyword: 'createTime', name: '创建时间', labelWidth: '70px', timeType: 'daterange', type: 'rangeDate' },
        { keyword: 'platformId', name: '平台', type: 'mulSelect', options: this.orderPlatformOption }
      ];
      return arr;
    },
    tableOutsideHeight() {
      return this.showMobilePage ? 200 : 0;
    }
  },
  created() {
    const end = Date.parse(new Date());
    const start = end - 2592000000;
    this.$set(this.paramsObj, 'createTime', [start, end]);
    this.fetchData(true);
    this.platformList();
  },
  methods: {
    hasRouteAuth,
    format,
    async platformList() {
      try {
        const result = await platformList();
        result.data = result.data.map(item => {
          item = {
            value: item.id,
            label: item.value
          };
          return item;
        });
        result.data.unshift({ value: -2, label: '--' });
        this.orderPlatformOption = result.data;
      } catch (error) {
        console.log(error);
      }
    },
    getParams() {
      const params = JSON.parse(JSON.stringify(this.paramsObj));
      paramsRangeFormat(this.rangeKeyArr, params);
      paramsAryToStr(this.arrayKeyArr, params);
      if (this.sortType || this.sortName) {
        params.sortName = this.sortName;
        params.sortType = this.sortType;
      }
      return params;
    },
    fetchData(reset = false) {
      if (reset) {
        this.page = 1;
      }
      this.listLoading = true;
      let params = this.getParams();
      params = {
        ...params,
        page: this.page,
        perPage: this.perPage
      };
      getImageList(params).then(res => {
        this.listLoading = false;
        if (res.code !== 200) {
          this.$message.error(res.message);
          return;
        }
        this.list = res.data;
        if (this.list.items.length) {
          this.list.items.forEach(item => {
            item.singleId = `${item.id}-${item.imageName}`; // id有重复，取id+imageName作为唯一值
          });
        }
      }).catch(err => {
        this.listLoading = false;
        console.log(err);
      });
    },
    selectAll() {
      const canPickItem = this.list.items.filter(item => item.platformTypeName !== '抖音' && item.orderId);
      if (!this.selectedData[this.selectedIndex] || this.selectedData[this.selectedIndex].data.length < canPickItem.length) { // 全选当前页
        canPickItem.forEach(item => {
          const { id, imageName, singleId } = item;
          if (!this.selectedIds.includes(singleId)) {
            if (this.selectedIndex > -1) {
              this.selectedData[this.selectedIndex].data.push({ id, imageName, singleId });
            } else {
              this.selectedData.push({ page: this.page, data: [{ id, imageName, singleId }] });
            }
          }
        });
      } else { // 全选反选
        this.selectedData[this.selectedIndex].data = [];
      }
    },
    clearMixinSelection() {
      this.selectedData = [
        { page: this.page, data: [] }
      ];
    },
    handleSelect(val, item) {
      if (val) {
        const { id, imageName, singleId } = item;
        if (this.selectedIndex > -1) {
          this.selectedData[this.selectedIndex].data.push({ id, imageName, singleId });
        } else {
          this.selectedData.push({ page: this.page, data: [{ id, imageName, singleId }] });
        }
      } else {
        this.selectedData.forEach(it => {
          if (it.page === this.page) {
            it.data = it.data.filter(it => it.singleId !== item.singleId);
          }
        });
      }
    },
    handleCancel() {
      this.isSelecting = false;
      this.clearMixinSelection();
    },
    preview(item) {
      window.open(item.url);
    },
    download(item) {
      downloadFile(item.url, item.imageName);
    },
    imageRePick(item) {
      const fn = (item) => {
        const { id, imageName } = item;
        const data = {
          id,
          imageName
        };
        this.pickLoadingIds.push(id);
        imageRePick(data).then(res => {
          this.clearId(id);
          this.fetchData();
        }).catch(err => {
          this.clearId(id);
          console.log(err);
        });
      };
      fn(item);
    },
    batchPick: _.debounce(function() {
      this.$confirm('是否确定替换采集？', '', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        lockScroll: false,
        customClass: 'del-message del-message-cancel',
        iconClass: 'del-icon',
        center: true
      }).then(() => {
        this.batchLoading = true;
        batchReplacePick(this.selectData).then(res => {
          if (res.code === 200) {
            this.batchLoading = false;
            this.fetchData(true);
            this.$message.success('任务提交成功');
            this.handleCancel();
          }
        }).catch(err => {
          this.batchLoading = false;
          console.error(err);
        });
      }).catch(() => {});
    }, 500),
    clearId(id) {
      const index = this.pickLoadingIds.findIndex(j => j === id);
      if (index > -1) { this.pickLoadingIds.splice(index, 1); }
    },
    queryClick() {
      this.fetchData(true);
    },
    queryEmpty() {
      this.paramsObj = {};
      this.fetchData(true);
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.clearMixinSelection();
      this.fetchData();
    },
    handleCurrentChange(page) {
      this.page = page;
      this.fetchData();
    },
    toOrder(item) {
      const url = this.$router.resolve({
        name: 'orderDetail',
        params: { orderId: item.orderId }
      });
      window.open(url.href, '_blank');
    },
    canPick(item) {
      return item.platformTypeName !== '抖音' && item.orderId;
    }
  }
};
</script>
<style lang="scss" scoped>
.image-list {
  margin: 16px 16px 0 16px !important;
  padding: 16px 16px 0 16px !important;
  background: #fff;
}
.img-wrap {
  display: flex;
  flex-wrap: wrap;
  @include scrollBar($x: hidden, $y: auto, $width: 8px);
}
.item {
  position: relative;
  height: 300px;
  margin-bottom: 8px;
  border-radius: 8px;
  padding: 0;
  background: transparent;
  box-shadow: 6px 4px 8px #dde1ea;
  .img {
    border-radius: 8px;
  }
  img {
    width: 100%;
    height: 100%;
  }
  .hover-item {
    position: absolute;
    display: none;
    flex-direction: column;
    top: 0px;
    bottom: 0px;
    right: 0px;
    left: 0px;
    background: linear-gradient(180deg,rgba(0,0,0,0.13), rgba(0,0,0,0.73) .9);
    border-radius: 8px;
    color: white;
    font-size: 12px;
    padding: 17px 12px 12px 12px;
    .check {
      flex-shrink: 0;
      white-space: nowrap;
      cursor: pointer;
    }
    .footer {
      display: flex;
      flex: 1;
      align-items: flex-end;
      .btn-wrap {
        display: flex;
        align-items: center;
        flex: 1;
        justify-content: flex-end;
        .img-btn {
          position: relative;
          display: flex;
          align-items: center;
          justify-content: center;
          width: 24px;
          height: 24px;
          border-radius: 50%;
          background: rgb(221, 221, 221, 0.1);
          margin-left: 8px;
          .img {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 16px;
            height: 16px;
            img {
              width: 100%;
              height: 100%;
            }
          }
          cursor: pointer;
        }
      }
    }
  }
  .select-box {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    z-index: 2;
    .select-mask {
      opacity: 0.6;
      background: #000;
      width: 100%;
      height: 100%;
      top: 0;
      left: 0;
    }
    &::v-deep {
      .el-checkbox {
        position: absolute;
        right: 16px;
        top: 16px;
        z-index: 3;
        .el-checkbox__inner {
          width: 24px;
          height: 24px;
          &::after {
            height: 12px;
            left: 9px;
            top: 4px;
            width: 4px;
            border: 2px solid #fff;
            border-left: 0;
            border-top: 0;
          }
        }
        .is-checked {
          .el-checkbox__inner {
            background: #406EFF;
          }
        }
      }
    }
  }
}
.item:hover {
  .hover-item {
    display: flex !important;
  }
}
.loading {
  position: fixed;
  bottom: 16px;
  left: 50%;
  height: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: transparent;
}
.no-bg {
  background: none !important;
}
@media only screen and (min-width: 0px) {
  .el-col-4 {
    width: 100%;
  }
}
@media only screen and (min-width: 400px) {
  .el-col-4 {
    width: 50%;
  }
}
@media only screen and (min-width: 768px) {
  .el-col-4 {
    width: 25%;
  }
}

@media only screen and (min-width: 992px) {
  .el-col-4 {
    width: 20%;
  }
}

@media only screen and (min-width: 1600px) {
  .el-col-4 {
    width: calc(100% / 6);
  }
}
.flex-1 {
  flex: 1 !important;
}
.cancel-btn-style {
  font-size: 14px;
  padding: 8px 20px;
  margin-left: 16px !important;
}
</style>
